package com.szyjjk.controller;

import com.alibaba.fastjson.JSONObject;
import com.szyjjk.entity.*;
import com.szyjjk.service.RunFilePathrService;
import com.szyjjk.service.RunPropertyServices;
import com.szyjjk.service.RunSiteService;
import com.szyjjk.service.SysHearWordService;
import com.szyjjk.util.DateUtil;
import com.szyjjk.util.UUIDUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.*;
import java.util.*;

/**
 * @program: szyjjk
 * @description: 读取map和dbf的之类数据 然后展示在页面
 * @author: yangyue
 * @create: 2020-05-13 10:35
 */
@Controller
@RequestMapping("/readMap")
public class ReadMapController {

    @Autowired
    private SysHearWordService sysHearWordService;

    @Autowired
    private RunFilePathrService runFilePathrService;
    @Autowired
    private RunPropertyServices runPropertyServices;
    @Autowired
    private RunSiteService runSiteService;


    /**
     * @return java.util.List<com.szyjjk.entity.RunHisData>
     * @Author yangyue
     * @Description //TODO 查询his 里面的数据
     * @Date 9:47 2020/6/19
     * @Param [beginTime, endTime, type, trie, fileID, site]
     **/
    @RequestMapping(value = "/queryHis.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<RunHisData> queryHis(String beginTime, String endTime, String type, String trie, String fileID, String site, String languageType, String dyMonth) {
        if (StringUtils.isNotEmpty(dyMonth)) {
            //不为空就是动态数据，时间默认就位最近一个月的时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.MONTH, -1);
            beginTime = DateUtil.dateToString(calendar.getTime());
            endTime = DateUtil.dateToString(new Date());
        }
        Date[] timeArray = DateUtil.StringToDate5(beginTime, endTime);
        Date begintime = timeArray[0];
        Date endtime = timeArray[1];
        RunProperty runProperty = this.runPropertyServices.findByIDPro(type);
        RunFilePath runFilePath = this.runFilePathrService.findById(fileID);
        List<RunHisData> runHisDataList = new ArrayList<RunHisData>();
        if ("oneY".equals(runFilePath.getFileSour())) {
            //查询一年的数据
            runHisDataList = this.sysHearWordService.findOneYData(runProperty.getProNamech(), site, trie, fileID, begintime, endtime, 0);
        } else if ("dataTh".equals(runFilePath.getFileSour()) || "1".equals(fileID)) {
            //查询同化数据
            if(begintime==null){
                runHisDataList = this.sysHearWordService.findOneYData(runProperty.getProNamech(), site, trie, fileID, begintime, endtime, 1);
            }else{
                Map<Integer,Date[]> mapTimeRange=DateUtil.conversionData(begintime,endtime);
                for(Map.Entry<Integer,Date[]> entry : mapTimeRange.entrySet()) {
                    int year=entry.getKey();
                    Date[] timeRange=entry.getValue();
                    List<RunHisData> runHisDataListEdfc = this.sysHearWordService.findOneYData(runProperty.getProNamech(), site, trie, "", timeRange[0], timeRange[1], 1);
                    for (RunHisData runHisData : runHisDataListEdfc) {
                        Calendar calendar=Calendar.getInstance();
                        calendar.setTime(runHisData.getHisTime());
                        calendar.set(Calendar.YEAR,year);
                        runHisData.setHisTime(calendar.getTime());
                        runHisDataList.add(runHisData);
                    }
                }
            }

//
        } else {
            runHisDataList = this.sysHearWordService.findHisByQuery(runProperty.getProNamech(), trie, fileID, begintime, endtime, site);
        }
        if (runHisDataList == null) {
            File file = new File(runFilePath.getFilePath() + runFilePath.getFileName());
            if (file.exists()) {
                //文件存在，但是没有数据，说明文件数据正在存储中
                RunHisData runHisData = new RunHisData();
                runHisData.setId("000");
                runHisDataList.add(runHisData);
            }
        }
        for (RunHisData runHisData : runHisDataList) {
            if ("en".equals(languageType)) {
                String zh = runHisData.getHisRemark();
                runHisData.setHisRemark(runHisData.getHisPro());
                runHisData.setHisPro(zh);
            }
        }

        return runHisDataList;
    }

    @RequestMapping(value = "/findOneMonthThreeData.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject findOneMonthThreeData(String beginTime, String endTime, String type, String trie, String site, String languageType) {
        JSONObject result = new JSONObject();
        Date begintime = null;
        Date endtime = null;
        if (StringUtils.isNotEmpty(beginTime)) {
            //不为空
            Date[] timeArray = DateUtil.StringToDate5(beginTime, endTime);
            begintime = timeArray[0];
            endtime = timeArray[1];
        } else {
            //为空
            begintime = DateUtil.addDateValue(new Date(), -1, "M");
            endtime = new Date();
        }
        //获取属性名
        RunProperty runProperty = this.runPropertyServices.findByIDPro(type);

        RunFilePath runFilePath = this.runFilePathrService.findByLikSOURTop1("timing", "sbw");
        List<RunHisData> runHisDataListSbw = this.sysHearWordService.findHisByQuery(runProperty.getProNamech(), trie, runFilePath.getId(), begintime, endtime, site);
        result.put("sbw", runHisDataListSbw);
        //只有这三个才查询其他
 //       if ("总磷".equals(runProperty.getProNamech()) || "总氮".equals(runProperty.getProNamech()) || "氨氮".equals(runProperty.getProNamech())) {
            //同化数据 得分两个阶段，一个是2020年内的数据，这样就不需要进行转化，第二个就是2020年外部的数据，得查的时候用2020年去查，然后查完再进行转化
            Map<Integer,Date[]> mapTimeRange=DateUtil.conversionData(begintime,endtime);
            List<RunHisData> runHisDataListEdfcAll=new ArrayList<>();
            for(Map.Entry<Integer,Date[]> entry : mapTimeRange.entrySet()) {
                int year=entry.getKey();
                Date[] timeRange=entry.getValue();
                List<RunHisData> runHisDataListEdfc = this.sysHearWordService.findOneYData(runProperty.getProNamech(), site, trie, "", timeRange[0], timeRange[1], 1);
                for (RunHisData runHisData : runHisDataListEdfc) {
                    Calendar calendar=Calendar.getInstance();
                    calendar.setTime(runHisData.getHisTime());
                    calendar.set(Calendar.YEAR,DateUtil.getYear());
                    runHisData.setHisTime(calendar.getTime());
                    runHisDataListEdfcAll.add(runHisData);
                }
            }
            result.put("edfc", runHisDataListEdfcAll);
            //查询浮标数据
            List<SysHardWareData> reulstHwd = this.sysHearWordService.findSysHarwareDateByNameBeginTime(UUIDUtils.gethardWareData(runProperty.getProNamech()), begintime, endtime);
            result.put("hwd", reulstHwd);
//        } else {
//            result.put("edfc", null);
//            result.put("hwd", null);
//        }

        result.put("time", DateUtil.dateToString(begintime) + " - " + DateUtil.dateToString(endtime));
        return result;
    }


    @RequestMapping(value = "/findFileType.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<RunFilePath> findFileType(String type) {
        return this.runFilePathrService.findFilePathByHz(type);
    }

    /**
     * @return java.util.List<com.szyjjk.entity.RunProperty>
     * @Author yangyue
     * @Description //TODO 查询属性列表  type 0 为模拟， 1 为硬件
     * @Date 9:31 2020/9/28
     * @Param []
     **/
    @RequestMapping(value = "/findHisDataType.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<RunProperty> findHisDataType(int type, String languageType) {
//        String arr1[] = {"温度", "盐度", "水位", "总氮", "总磷", "氨氮", "硝酸盐", "氮", "无机磷", "溶解氧", "悬浮颗粒", "三种细菌（Ecoli）", "三种细菌（Fcoli）", "三种细菌（Encoc）", "叶绿素a"};
        //[{"value":"总氮","min":"0.56","max":"9.5","default":"1.9"},{"value":"总磷","min":"0.03","max":"0.86","default":"0.14"},{"value":"氨氮","min":"0.006","max":"5.2","default":"0.257"},{"value":"硝酸盐","min":"0.031","max":"3.4","default":"1.06"},{"value":"无机磷","min":"0.008","max":"0.41","default":"0.117"},{"value":"溶解氧","min":"1.5","max":"9.6","default":"5.8"},{"value":"悬浮颗粒","min":"1.5","max":"150","default":"22"},{"value":"温度","min":"13.8","max":"31.9","default":"25"},{"value":"盐度","min":"0.2","max":"31.7","default":"18"},{"value":"三种细菌（Ecoli）","min":"1","max":"6.9","default":"2.85"},{"value":"三种细菌（Fcoli）","min":"1","max":"6.9","default":"2.85"},{"value":"三种细菌（Encoc）","min":"1","max":"6.9","default":"2.85"},{"value":"叶绿素a","min":"0.5","max":"100","default":"4.39"}]
        //"温度", "盐度", "总氮", "总磷", "氨氮", "硝酸盐","无机磷", "溶解氧", "悬浮颗粒", "三种细菌（Ecoli）", "三种细菌（Fcoli）", "三种细菌（Encoc）", "叶绿素a"
        //排序分别是 名称、标准值最大值、标准值最小值、默认值、异常值、
        List<RunProperty> runPropertyMapperList = new ArrayList<>();
        if (type == -1) {
            runPropertyMapperList = this.runPropertyServices.findProAll();
        } else {
            runPropertyMapperList = this.runPropertyServices.findByFileType(type);
        }
        for (RunProperty runProperty : runPropertyMapperList) {
            if (runProperty.getProNameen() == null) {
                runProperty.setProRemark(runProperty.getProNamech());
            } else {
                if ("en".equals(languageType)) {
                    runProperty.setProRemark(runProperty.getProNameen());
                } else {
                    runProperty.setProRemark(runProperty.getProNamech() + "(" + runProperty.getProNameen() + ")");
                }

            }
        }
        return runPropertyMapperList;
    }

    @RequestMapping(value = "getsitevalueinsql",method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public List<RunSite> getsitevalueinsql(){
        return this.runSiteService.findAllSite();
    }
    /***
     * @Author yangyue
     * @Description //TODO 分页查询属性表
     * @Date 11:00 2020/10/27
     * @Param [languageType, pageNo]
     * @return com.alibaba.fastjson.JSONObject
     **/
    @RequestMapping(value = "/findPagePro.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject findPagePro(String languageType, int pageNo) {
        JSONObject jsonObject = new JSONObject();
        int pageSize = 10;
        List<RunProperty> runPropertyMapperList = this.runPropertyServices.findPageCount((pageNo - 1) * pageSize, pageSize);
        for (RunProperty runProperty : runPropertyMapperList) {
            if ("en".equals(languageType)) {
                runProperty.setProNamech(runProperty.getProNameen());
            }
//            runProperty.setProRed(runProperty.getProRed().replaceAll("&","<br/>"));
        }
        jsonObject.put("list", runPropertyMapperList);
        jsonObject.put("count", this.runPropertyServices.findProAllCount());
        return jsonObject;
    }


    @RequestMapping(value = "/updatePro.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public int updatePro(String id, String redRange, String yellowRange, String greenRange, String unit) {
        RunProperty runProperty = this.runPropertyServices.findByIDPro(id);
        if (runProperty != null) {
            redRange = redRange.replaceAll(" ∞", "+∞").replaceAll("@", "&");
            runProperty.setProRed(redRange);
            runProperty.setProYellow(yellowRange);
            runProperty.setProGreen(greenRange);
            if ("null".equals(unit)) {
                unit = "";
            }
            runProperty.setProUnit(unit);
            this.runPropertyServices.editRunProperty(runProperty);
            return 1;
        } else {
            return 0;
        }

    }


    /**
     * @return java.lang.Object
     * @Author yangyue
     * @Description //TODO 修改
     * @Date 9:32 2020/9/28
     * @Param []
     **/
    @RequestMapping(value = "/UpdataHisData.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object UpdataHisData() {
        List<RunHisData> allHist = this.sysHearWordService.findAllHisData();
        for (RunHisData runHisData : allHist) {
            Date timeHist = runHisData.getHisTime();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(timeHist);
            calendar.set(Calendar.YEAR, 2020);
            calendar.set(Calendar.MONTH, 3);
            runHisData.setHisTime(calendar.getTime());
            this.sysHearWordService.editRunHisData(runHisData);
        }
        return "ok";
    }

    @RequestMapping(value = "/analysisTest.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String analysisTest() {
        RunFilePath runFilePath = new RunFilePath();
        runFilePath.setFilePath("D:\\SZwater\\WateraModels\\test\\");
        runFilePath.setFileName("20200605155216_test2_r.his");
        runFilePath.setId("e6ce6d51e75e4b20b763a7855f5a0622");
        analysisHis(runFilePath);
        return "ok";
    }


    /**
     * @return java.lang.Object
     * @Author yangyue
     * @Description //TODO 解析His 传入对应的实体，如果没有的话就去查询最新的HIS文件
     * @Date 16:54 2020/5/26
     * @Param [runFilePath]
     **/
    @RequestMapping(value = "/analysisHis.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String analysisHis(RunFilePath runFilePath) {
        if (runFilePath.getId() == null) {
            List<RunFilePath> runFilePathList = this.runFilePathrService.findFilePathByHz("his");
            if (runFilePathList.size() != 0) {
                runFilePath = runFilePathList.get(0);
            } else {
                return "暂无数据";
            }
        }
        try {
           // this.sysHearWordService.redBinary(runFilePath.getFilePath() + runFilePath.getFileName(), runFilePath.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "执行完成";
    }


}